<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>订单功能测试</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .test-section { margin: 20px 0; padding: 15px; border: 1px solid #ccc; }
        .success { color: green; }
        .error { color: red; }
        .info { color: blue; }
        button { margin: 5px; padding: 10px; }
        .test-buttons { display: flex; flex-wrap: wrap; gap: 10px; }
        .test-btn { padding: 8px 12px; background: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; }
        .test-btn:hover { background: #0056b3; }
        .order-item { border: 1px solid #ddd; margin: 10px 0; padding: 10px; }
    </style>
</head>
<body>
    <h1>订单功能测试</h1>
    
    <div class="test-section">
        <h3>1. 模拟用户登录</h3>
        <button onclick="simulateLogin()">模拟Mike登录</button>
        <div id="loginStatus"></div>
    </div>
    
    <div class="test-section">
        <h3>2. 创建测试订单</h3>
        <button onclick="createTestOrder()">创建测试订单</button>
        <div id="createOrderStatus"></div>
    </div>
    
    <div class="test-section">
        <h3>3. 测试订单功能</h3>
        <div class="test-buttons">
            <button class="test-btn" onclick="testGetOrders()">获取订单列表</button>
            <button class="test-btn" onclick="testOrderDetail()">获取订单详情</button>
            <button class="test-btn" onclick="openOrdersPage()">打开订单页面</button>
        </div>
    </div>
    
    <div class="test-section">
        <h3>4. 订单数据</h3>
        <div id="ordersData"></div>
    </div>
    
    <div class="test-section">
        <h3>5. 控制台日志</h3>
        <div id="consoleLog"></div>
    </div>

    <!-- 引入必要的脚本 -->
    <script src="js/api.js"></script>
    <script src="js/auth.js"></script>
    
    <script>
        // 重写console.log来显示在页面上
        const originalLog = console.log;
        const originalWarn = console.warn;
        const originalError = console.error;
        
        function addToConsole(message, type = 'info') {
            const logDiv = document.getElementById('consoleLog');
            const timestamp = new Date().toLocaleTimeString();
            logDiv.innerHTML += `<div class="${type}">[${timestamp}] ${message}</div>`;
            logDiv.scrollTop = logDiv.scrollHeight;
        }
        
        console.log = function(...args) {
            originalLog.apply(console, args);
            addToConsole(args.join(' '), 'info');
        };
        
        console.warn = function(...args) {
            originalWarn.apply(console, args);
            addToConsole(args.join(' '), 'error');
        };
        
        console.error = function(...args) {
            originalError.apply(console, args);
            addToConsole(args.join(' '), 'error');
        };
        
        // 模拟用户登录
        function simulateLogin() {
            const statusDiv = document.getElementById('loginStatus');
            try {
                const userData = {
                    username: 'Mike',
                    user_id: 'USER001',
                    email: 'mike@example.com',
                    phone: '1234567890',
                    user_type: 'Customer',
                    token: 'test-token-mike'
                };
                
                localStorage.setItem('currentUser', JSON.stringify(userData));
                localStorage.setItem('userData', JSON.stringify(userData));
                localStorage.setItem('authToken', userData.token);
                
                if (window.authManager) {
                    window.authManager.currentUser = userData;
                    window.authManager.isLoggedIn = true;
                    window.authManager.userType = userData.user_type;
                }
                
                statusDiv.innerHTML = '<div class="success">✓ Mike用户登录成功</div>';
                console.log('Mike用户登录成功:', userData);
            } catch (error) {
                statusDiv.innerHTML = '<div class="error">✗ 登录失败: ' + error.message + '</div>';
                console.error('登录失败:', error);
            }
        }
        
        // 创建测试订单
        async function createTestOrder() {
            const statusDiv = document.getElementById('createOrderStatus');
            try {
                const orderData = {
                    items: [
                        {
                            productId: 'F001',
                            product_name: '东北大米',
                            price: 115.3,
                            quantity: 2
                        },
                        {
                            productId: 'F007',
                            product_name: '广东腊肠',
                            price: 22.87,
                            quantity: 1
                        }
                    ],
                    shippingAddress: {
                        name: '张三',
                        phone: '13800138000',
                        address: '北京市朝阳区三里屯街道工体北路8号院'
                    },
                    paymentMethod: 'alipay',
                    discount: 10
                };
                
                const result = await window.api.createOrder(orderData);
                console.log('创建订单结果:', result);
                
                if (result.success) {
                    statusDiv.innerHTML = '<div class="success">✓ 测试订单创建成功</div>';
                    console.log('订单详情:', result.data);
                } else {
                    statusDiv.innerHTML = '<div class="error">✗ 创建订单失败: ' + result.error + '</div>';
                }
            } catch (error) {
                statusDiv.innerHTML = '<div class="error">✗ 创建订单错误: ' + error.message + '</div>';
                console.error('创建订单错误:', error);
            }
        }
        
        // 测试获取订单列表
        async function testGetOrders() {
            try {
                const result = await window.api.getOrders();
                console.log('获取订单列表结果:', result);
                
                if (result.success) {
                    const orders = result.data.orders || [];
                    updateOrdersDisplay(orders);
                    console.log('订单数量:', orders.length);
                } else {
                    console.error('获取订单失败:', result.error);
                }
            } catch (error) {
                console.error('获取订单错误:', error);
            }
        }
        
        // 测试获取订单详情
        async function testOrderDetail() {
            try {
                // 先获取订单列表
                const ordersResult = await window.api.getOrders();
                if (ordersResult.success && ordersResult.data.orders.length > 0) {
                    const firstOrder = ordersResult.data.orders[0];
                    const detailResult = await window.api.getOrderDetail(firstOrder.order_number);
                    console.log('订单详情:', detailResult);
                } else {
                    console.log('没有订单可查看详情');
                }
            } catch (error) {
                console.error('获取订单详情错误:', error);
            }
        }
        
        // 打开订单页面
        function openOrdersPage() {
            console.log('打开订单页面...');
            window.open('orders.html', '_blank');
        }
        
        // 更新订单显示
        function updateOrdersDisplay(orders) {
            const ordersDiv = document.getElementById('ordersData');
            
            if (orders.length === 0) {
                ordersDiv.innerHTML = '<div class="info">暂无订单</div>';
                return;
            }
            
            ordersDiv.innerHTML = orders.map(order => `
                <div class="order-item">
                    <h4>订单号: ${order.order_number}</h4>
                    <p>状态: ${order.status}</p>
                    <p>总金额: ¥${order.total_amount}</p>
                    <p>创建时间: ${new Date(order.created_at).toLocaleString()}</p>
                    <p>商品数量: ${order.items.length}件</p>
                </div>
            `).join('');
        }
        
        // 页面加载完成后运行测试
        window.addEventListener('load', () => {
            console.log('页面加载完成，订单功能测试准备就绪');
            
            // 检查模块加载状态
            setTimeout(() => {
                console.log('模块加载状态:');
                console.log('- API:', !!window.api);
                console.log('- AuthManager:', !!window.authManager);
            }, 100);
        });
    </script>
</body>
</html>
